package com.qf.test;

import com.qf.utils.ESUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.metrics.ParsedExtendedStats;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;

import java.io.IOException;

/**
 * 聚合函数
 */
public class AggDemo {

    @Test
    public void extendsStat() throws IOException {
        //1. 创建指定的Request对象，并设置索引名称和doc_id
        SearchRequest request = new SearchRequest();
        request.indices("sms-logs-index");

        //2. 设置添加的数据给Request对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //2.1 设置聚合函数信息
        sourceBuilder.aggregation(AggregationBuilders.extendedStats("hahaha").field("fee"));
        //2.2 设置到Request中
        request.source(sourceBuilder);

        //3. 通过连接对象将Request发送给ES，并接受Response
        SearchResponse resp = ESUtil.getClient().search(request, RequestOptions.DEFAULT);

        //4. 通过Response判断添加是否成功
        Aggregations aggregations = resp.getAggregations();
        ParsedExtendedStats hahaha = aggregations.get("hahaha");    // 向下转型
        System.out.println(hahaha.getCount());
    }
}
